﻿var RestClient = {};

(function(){
    // public functions

    RestClient.createApp = function (app) {
        queueAction(wakeupCreateApp, {app:app});
    };

    // private functions
    var queueAction = function (actionCallback, options) {
        if (typeof document.restq == "undefined") document.restq = [];
        if (!actionCallback) {
            return;
        }
        var completeAction = function () {
            document.restq.shift();
            for (var i = 0; i < document.restq.length; i++) {
                if (document.restq[i].options.app) {
                    contextMgr.applyToContext('app', document.restq[i].options.app);
                }
                else if (document.restq[i].options.user) {
                    if (!contextData.app.appFamily || !contextData.app.appFamily.user) {
                        contextMgr.applyToContext('app', {appFamily:{user:document.restq[i].options.user}}, contextData.app);
                    }
                    else {
                        contextMgr.applyToContext('app', document.restq[i].options.user, contextData.app.appFamily.user);
                    }
                }
            }
            if (document.restq.length > 0) {
                try {
                    document.restq[0].action(document.restq[0].options, null, completeAction);
                }
                catch (e) {
                    completeAction();
                }
            }
        };
        document.restq.push({action:actionCallback, options:options ? options : {}});
        if (document.restq.length == 1) {
            try {
                document.restq[0].action(document.restq[0].options, null, completeAction);
            }
            catch (e) {
                completeAction();
            }
        }
    };
})();